package controller

import (
	"VoteProgram/dao"
	"VoteProgram/models"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"path"
)

//访问主页
func HomePage(c *gin.Context) {
	var All_students_list []map[string] models.Students
	var Students_slice []models.Students

	//访问主页访问量+1
	models.VisitorPlus1()
	//获取主页访问量
	Visitor := models.GetVisitors()
	//查询所有参赛人员
	dao.DB.Order("thumbs desc").Find(&Students_slice)
	//参赛人数
	People := len(Students_slice)
	var Thumbs int32 = 0
	//将所有信息做成map切片形式用于传入前端页面
	for _,v := range Students_slice{
		student_info := make(map[string] models.Students)
		student_info["student"]=v
		Thumbs += v.Thumbs
		All_students_list = append(All_students_list, student_info)
	}
	c.HTML(http.StatusOK, "index.tmpl",gin.H{
		"all_students" : All_students_list,//前端模板循环接收
		"people":People,
		"thumbs":Thumbs,
		"visitors":Visitor.Num,
	})
}

//我要报名页面
func Sign_up(c *gin.Context)  {
	c.HTML(http.StatusOK, "sign-up.tmpl",gin.H{
	})
}

//点赞页面
func Give_thumb(c *gin.Context){
	id := c.Param("id")
	var If_thumb string
	var BackColor string
	_,today := dao.GetTime()
	//获取访问点赞人员的ip
	Cli_ip := c.ClientIP()
	fmt.Println(Cli_ip)
	if_thumb :=models.IfThumbs(Cli_ip,today)

	if if_thumb == true{
		//点赞数加一
		BackColor = "#6efa17"
		models.ThumbsIpPlus1(Cli_ip)
		models.ThumbsPlus1(id)
		If_thumb = "点赞成功！"
	}else {
		BackColor = "#ff831d"
		If_thumb = "点赞失败,每天可点三个赞！"
	}

	Student_info := models.GetStudentInfo(id)
	c.HTML(http.StatusOK,"detail.tmpl",gin.H{
		"name":Student_info.Name,
		"thumbs":Student_info.Thumbs,
		"img":Student_info.Img,
		"if_thumb":If_thumb,
		"backcolor":BackColor,
	})
}

//活动介绍页面
func Act_intro(c *gin.Context)  {
	c.HTML(http.StatusOK, "act-intro.tmpl",gin.H{})
}

//上传信息页面
func Sign_up_post(c *gin.Context)  {
	//获取form提交的内容
	name :=c.PostForm("name")
	qq := c.PostForm("qq")
	fmt.Println(qq)
	img,err := c.FormFile("img")
	if err != nil{
		c.JSON(http.StatusBadRequest,gin.H{
			"出错了":err.Error(),
		})
	}else {
		//将读取的文件保存本地（服务端本地）
		//dst := fmt.Sprintf("./%s",f.Filename)
		dst := path.Join("./static/img",img.Filename)
		img_url := "../"+ dst
		err := c.SaveUploadedFile(img,dst)
		if err!= nil{
			c.JSON(http.StatusBadRequest,gin.H{
				"出错了":err.Error,
			})
		}
		new_student := models.Students{Name: name,Img: img_url,Thumbs: 0,QQ:qq}
		result :=dao.DB.Create(&new_student)
		if result.Error != nil{
			c.JSON(http.StatusBadRequest,gin.H{
				"出错了":result.Error,
			})
		}
		c.Redirect(http.StatusMovedPermanently,"../index")
	}
}
